package cn.leftshine.myithome;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import cn.leftshine.myithome.beans.NewsItem;
import cn.leftshine.myithome.helper.BottomNavigationViewHelper;
import cn.leftshine.myithome.ui.fragment.LapinFragment;
import cn.leftshine.myithome.ui.fragment.MeFragment;
import cn.leftshine.myithome.ui.fragment.NewsFragment;
import cn.leftshine.myithome.ui.fragment.NewsListFragment;
import cn.leftshine.myithome.ui.fragment.QuanFragment;

public class MainActivity extends AppCompatActivity implements NewsFragment.OnFragmentInteractionListener,LapinFragment.OnFragmentInteractionListener,QuanFragment.OnFragmentInteractionListener,MeFragment.OnFragmentInteractionListener,NewsListFragment.OnListFragmentInteractionListener{

    private MenuItem menuItem;
    private BottomNavigationView bottomNavigationView;
    private NewsFragment newsFragment;
    private LapinFragment lapinFragment;
    private QuanFragment quanFragment;
    private MeFragment meFragment;
    private SoundPool soundPool;
    private int soundID;
    private Fragment mCurrentFragment;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //获取样式中的属性值
            TypedValue typedValue = new TypedValue();
            this.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
            int[] attribute = new int[] { android.R.attr.colorPrimary };
            TypedArray array = this.obtainStyledAttributes(typedValue.resourceId, attribute);
            int color = array.getColor(0, Color.TRANSPARENT);
            array.recycle();

            window.setStatusBarColor(color);
        }

        setContentView(R.layout.activity_main);
        bindViews();
        initSound();

        if (findViewById(R.id.fragment_container) != null) {

            // 不过，如果我们要从先前的状态还原，则无需执行任何操作而应返回，否则
            // 就会得到重叠的 Fragment。
            if (savedInstanceState != null) {
                return;
            }

            // 创建一个要放入 Activity 布局中的新 Fragment
            newsFragment = new NewsFragment();
            // 如果此 Activity 是通过 Intent 发出的特殊指令来启动的，
            // 请将该 Intent 的 extras 以参数形式传递给该 Fragment
            newsFragment.setArguments(getIntent().getExtras());
            // 将该 Fragment 添加到“fragment_container” FrameLayout 中
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, newsFragment).commit();
        }

    }
    @SuppressLint("NewApi")
    private void initSound() {
        if((android.os.Build.VERSION.SDK_INT) >= 21){
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            soundPool = new SoundPool.Builder()
                    .setAudioAttributes(audioAttributes)
                    .build();
        }
        else{
            soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        }

        soundID = soundPool.load(this, R.raw.click, 1);
    }

    private void bindViews() {
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        //利用反射去掉菜单数量 >3 的选中效果
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                playSound();
                bottomNavigationView.playSoundEffect(soundID);
                switch (item.getItemId()) {
                    case R.id.bottom_news:
                        if (newsFragment == null)
                            //newsFragment = new NewsFragment();
                            newsFragment = new NewsFragment();
                        replaceFragment(newsFragment);
                        break;
                    case R.id.bottom_lapin:
                        if (lapinFragment == null)
                            lapinFragment = new LapinFragment();
                        replaceFragment(lapinFragment);
                        break;
                    case R.id.bottom_quan:
                        if (quanFragment == null)
                            quanFragment = new QuanFragment();
                        replaceFragment(quanFragment);
                        break;
                    case R.id.bottom_me:
                        if (meFragment == null)
                            meFragment = new MeFragment();
                        replaceFragment(meFragment);
                        break;
                }
                return true;
            }

        });
    }

    private void replaceFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // 将 fragment_container View 中的内容替换为此 Fragment，
        // 然后将该事务添加到返回堆栈，以便用户可以向后导航
        transaction.replace(R.id.fragment_container, fragment);
        //transaction.addToBackStack(null);
        // 执行事务
        transaction.commit();
        mCurrentFragment = fragment;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(mCurrentFragment instanceof NewsFragment )
        {

        }else if(mCurrentFragment instanceof LapinFragment) {
            if (lapinFragment.webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
                lapinFragment.webView.goBack(); // goBack()表示返回webView的上一页面
                return true;
            }
        }else if(mCurrentFragment instanceof QuanFragment){
            if (quanFragment.webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
                quanFragment.webView.goBack(); // goBack()表示返回webView的上一页面
                return true;
            }
        }else if(mCurrentFragment instanceof MeFragment){

        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    private void playSound() {
        soundPool.play(
                soundID,
                0.5f,   //左耳道音量【0~1】
                0.5f,   //右耳道音量【0~1】
                0,     //播放优先级【0表示最低优先级】
                0,     //循环模式【0表示循环一次，-1表示一直循环，其他表示数字+1表示当前数字对应的循环次数】
                1     //播放速度【1是正常，范围从0~2】
        );
    }

    @Override
    public void onListFragmentInteraction(NewsItem item) {
        Log.i("pcj", "onListFragmentInteraction: a item clicked:"+item.title);
        Intent intent =new Intent(MainActivity.this,NewsDetailActivity.class);
        intent.putExtra("title",item.title);
        intent.putExtra("link",item.link);
        intent.putExtra("pubDate",item.pubDate);
        intent.putExtra("content",item.description);
        startActivity(intent);
    }
}
